package com.nbsaas.boot.lock.impl;

import com.nbsaas.boot.lock.api.LockService;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class MemoryLockService implements LockService {

    private final ConcurrentMap<String, Lock> lockMap = new ConcurrentHashMap<>();

    @Override
    public boolean lock(String key) {
        Lock lock = lockMap.computeIfAbsent(key, k -> new ReentrantLock());
        // 尝试立即获取锁，不阻塞
        return lock.tryLock();
    }

    @Override
    public boolean lock(String key, long timeout, TimeUnit unit) {
        Lock lock = lockMap.computeIfAbsent(key, k -> new ReentrantLock());
        try {
            return lock.tryLock(timeout, unit);  // 尝试获取锁，超时则返回false
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            return false;
        }
    }

    @Override
    public boolean unlock(String key) {
        Lock lock = lockMap.get(key);
        if (lock != null) {
            lock.unlock();  // 释放锁
            return true;
        }
        return false;
    }

    @Override
    public boolean isLocked(String key) {
        Lock lock = lockMap.get(key);
        return lock != null && ((ReentrantLock) lock).isLocked();
    }
}
